<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 2022-06-25
 * Time: 14:49
 */

namespace plugin\thinkphp\middleware;


use ExAdmin\ui\support\Token;
use ExAdmin\ui\token\AuthException;
use plugin\thinkphp\Admin;
use think\exception\HttpResponseException;
use think\Request;

class AuthMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        list($class, $function) = Admin::getDispatch();
        if ($class != 'system' && $class != 'login') {
            try {
                Token::auth();
            } catch (AuthException $exception) {
                throw new HttpResponseException(json(['message' => $exception->getMessage(), 'code' => $exception->getCode()], 401));
            }
        }
        return $next($request);
    }
}